import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//TCP服务器
public class TcpEchoClient {
    ServerSocket serverSocket = null;

    public TcpEchoClient(int id) throws IOException {
        //指定端口以便于客服端连接
        serverSocket = new ServerSocket(id);
    }

    public void stack() throws IOException {
        System.out.println("服务器启动!");
        ExecutorService service = Executors.newCachedThreadPool();
        while(true) {

            //建立连接,有请求则连接,无则阻塞等待
            Socket socket = serverSocket.accept();

            //处理连接以后的数据
            //版本2
            service.submit(()->{
                try {
                    processComnection(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            //版本1
           /* Thread t = new Thread(()->{
                try {
                    processComnection(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            t.start();*/
        }
    }

    public void processComnection(Socket socket) throws IOException {
        //获取开始时的客户端的IP和端口号
        System.out.printf("[%s:%d] 建立连接\n",socket.getInetAddress().toString(),socket.getPort());

        try( InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                if(!scanner.hasNext()) {
                    //断开连接则断开输入输出流
                    System.out.printf("[%s:%d] 断开连接\n", socket.getInetAddress().toString(), socket.getPort());
                    break;
                }
                //读取请求数据并解析
                String str = scanner.next();
                //请求回应
                String str1 = persson(str);
                //响应客服端
                printWriter.println(str1);
                //刷新缓冲区
                printWriter.flush();

                System.out.printf("[%s:%d] 请求:%s 响应:%s\n", socket.getInetAddress().toString(), socket.getPort(),
                        str, str1);
            }
        }finally {
            //需要关闭Socket文件流,防止内存泄漏
            //TCP和UDP的区别在于,UDP是一个无连接服务器,随时请求随时响应,所以不需要关闭资源.
            //而TCP每次建立连接的客户端都不同,不关就会导致内存泄漏
            socket.close();
        }
    }

    public String persson(String str) {
        return str;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcp = new TcpEchoClient(2000);
        tcp.stack();
    }
}
